package com.itpeng.controller;


import com.itpeng.entity.Result;
import com.itpeng.exception.HealthException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @Aythor:彭彦钦
 * @Data: 2020/9/19  20:47
 */

/**
 * 全局捕获异常处理类
 */
@RestControllerAdvice
public class HealExceptionAdvice {

    // 定义日志对象，方便输出日志到文件中
    private static final Logger log = LoggerFactory.getLogger(HealExceptionAdvice.class);

    /**
     * 处理自定义的HealthException异常
     * @param healthException
     * @return
     */
    @ExceptionHandler(HealthException.class)
    public Result handleHealthException(HealthException healthException){
        return new Result(false, healthException.getMessage());
    }

    /**
     * 密码错误
     * @param badCredentialsException
     * @return
     */
    @ExceptionHandler(BadCredentialsException.class)
    public Result handBadCredentialsException(BadCredentialsException badCredentialsException){
        return handleUserPassword();
    }

    /**
     * 用户名不存在
     * @param he
     * @return
     */
    @ExceptionHandler(InternalAuthenticationServiceException.class)
    public Result handInternalAuthenticationServiceException(InternalAuthenticationServiceException he){
        return handleUserPassword();
    }

    private Result handleUserPassword(){
        return new Result(false, "用户名或密码错误");
    }
    /**
     * 权限不足错误
     * @param accessDeniedException
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    public Result handleAccessDeniedException(AccessDeniedException accessDeniedException){
        return new Result(false, "您没有权限访问或使用该功能");
    }
    /**
     * 处理未知的系统异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e){
        log.debug("发生异常", e);
        return new Result(false, "发生未知错误，操作失败，请联系管理员");
    }

}
